/**
 * Created by Freeman on 2017/7/13.
 */
import reqwest from 'reqwest';

import ascp from '../../../../src/js/ascp.js';
import { timeAgo, numFormat } from '../../../../src/js/utils.js';
import { insertQihuAd } from './qhAdMonitor.js';

export default class FeedList {

  constructor(opts) {

    // 信息流数据
    this.list = [];
    this.lock = false;

    // 置顶
    this._stickItem = null;

    // 刷新提示
    this._refreshItem = null;

    // 初始列表
    this._initList = null;

    this.params = {
      category: '__all__',
      utm_source: 'toutiao',
      widen: 1,
      tadrequire: true
    };

    this.params.category = this._category = opts.category || '__all__';
    this._url = opts.url + '?';
    this._qhAddSupport = opts.qhAdSupport;

    this._sourceFlags = {}; // 控制媒体头像颜色
    this._frequency = 0;    // 请求频次

    // 列表初始化
    this._initList = this._feedListInit(opts.initList || []);
  }

  /**
   * feed初始化
   */
  _feedListInit(list) {
    return this._dataPreHandle(list);
  }

  /**
   * 获取返回列表
   */
  getList() {
    let ret = this.list;

    if (this._refreshItem) {
      ret = [].concat(ret.slice(0, this._refreshItem._index), [this._refreshItem], ret.slice(this._refreshItem._index));
    }
    if (this._stickItem) ret = this._stickItem.concat(ret);
    if (this._initList) ret = this._initList.concat(ret);
    return ret;
  }

  /**
   * 刷新
   */
  refresh(callback, completeCbk) {
    this._getData('refresh', callback, completeCbk);
  }

  /**
   * loadmore
   */
  loadMore(callback, completeCbk) {
    this._getData('loadmore', callback, completeCbk);
  }

  /**
   * 时间统一跟新
   */
  updateTime() {
    let ret = this.getList();

    ret.forEach((item) => {
      item.time_ago = timeAgo(item.behot_time);
    });

    return ret;
  }

  /**
   * 不感兴趣文章
   */
  dislikeItem(id) {
    let _index = -1;

    var itemDelete = function(arr) {
      let index = -1;
      arr = arr || [];

      for (let i = 0, len = arr.length; i < len; i++) {
        if (arr[i].group_id == id) {
          index = i;
          break;
        }
      }
      if (index >= 0) {
        arr.splice(index, 1);
      }
      return index;
    };

    // 初始列表
    _index = itemDelete(this._initList);

    // 置顶
    if (_index === -1) {
      _index = itemDelete(this._stickItem);
      if (_index === 0) this._stickItem = null;
    }

    // 普通列表
    if (_index === -1) {
      _index = itemDelete(this.list);
      if (_index !== -1 && this._refreshItem) {
        _index >= this._refreshItem._index ? this._refreshItem._index : --this._refreshItem._index;
      }
    }

    return this.getList();
  }

  // 数据请求
  _getData(type, callback, completeCbk) {
    if (this.lock) return;
    this.lock = true;

    this._setParams(type);

    let defaultCbk = () => {
      this.lock = false;
      completeCbk && completeCbk();
    };

    reqwest({
      url: this.url,
      data: this.params,
      success: (res) => {
        let data = res || {},
          listTmp = data.data || [],
          nextTime = data.next && data.next.max_behot_time;

        if (data.message === 'success' && listTmp.length) {
          this._qihuAdInsert(listTmp);
          listTmp = this._dataPreHandle(listTmp);

          if (type === 'refresh') {
            this._refreshItem = {
              refresh_mode: true,
              behot_time: nextTime,
              time_ago: timeAgo(nextTime),
              _index: listTmp.length
            };
            this.list = listTmp.concat(this.list);
          } else {
            this.list = this.list.concat(listTmp);
          }

          callback && callback(this.getList(), listTmp.length);
        }

        defaultCbk();
      },
      error: () => {
        defaultCbk();
      }
    });
  }

  // 奇虎广告处理
  _qihuAdInsert(list) {
    if (this._qhAddSupport) {
      if (this._frequency === 0 || this._frequency%2 !== 0) {
        insertQihuAd(list);
      }
      this.params.tadrequire = !this.params.tadrequire;
      this._frequency++;
    }
  }

  // 数据预处理
  _dataPreHandle(list) {
    if (!Array.isArray(list) || list.length === 0) return [];

    let stick_index = -1;
    this._stickItem = null;

    // 爬虫蜜罐数据
    if (list[list.length-1].honey) {
      list.pop();
    }

    list.forEach((item, index) => {
      this._dataChange(item);

      if (item.is_stick) stick_index = index;
    });

    // 置顶文章处理
    if (stick_index >= 0) {
      this._stickItem = list.splice(stick_index, 1);
    }

    window.ttAnalysis && window.ttAnalysis.send('event', {
      ev: 'article_show_count',
      ext_id: list.length
    });

    return list;
  }

  // 数据格式转换
  _dataChange(item) {
    item.time_ago = timeAgo(item.behot_time);
    item.comments_count = numFormat(item.comments_count);
    (this._category === '__all__') && this._tagHandle(item);
    this._mediaHandle(item);
  }

  // 媒体头像处理
  _mediaHandle(item) {
    if (!item.media_url) {
      let source = (item.source && item.source.replace(/\s*/ig, ''));

      item.source_tag = source ? source.slice(0, 1) : '';

      if (this._sourceFlags[source] === undefined) {
        this._sourceFlags[source] = Math.floor(Math.random() * 6);
      }

      item.avatar_style = 'avatar-style-' + this._sourceFlags[source];
    }
  }

  // 频道标签展示处理
  _tagHandle(item) {
    let channelColor = {
      '热点': 'hot',
      '视频': 'video',
      '图片': 'image',
      '社会': 'society',
      '汽车': 'car',
      '体育': 'sport',
      '财经': 'finance',
      '科技': 'technology',
      '娱乐': 'entertainment'
    };

    if (item.chinese_tag) {
      item.tag_style = 'tag-style-' + (channelColor[item.chinese_tag] || 'other');
    }
  }

  // 请求参数控制
  _setParams(type) {
    let antiParam = ascp();
    let getTime = 0;

    Object.assign(this.params, {
      as: antiParam.as,
      cp: antiParam.cp
    });

    this.url = this._url;
    if (type === 'refresh') {
      getTime = this.list.length > 0 ? this.list[0].behot_time : 0;
      this.url += `min_behot_time=${getTime}`;
    } else {
      getTime = this.list.length > 0 ? this.list[this.list.length - 1].behot_time : 0;
      this.url += `max_behot_time=${getTime}`;
    }
  }
}



// WEBPACK FOOTER //
// ./~/byted-toutiao-pc-business-components/components/feed/src/_data/FeedList.js
